<template>
  <div>
    <a-menu
      v-model:selectedKeys="state.selectedKeys"
      style="width: 256px"
      mode="inline"
      :open-keys="state.openKeys"
      :items="items"
      @open-change="onOpenChange"
    ></a-menu>
  </div>
</template>
<script lang="ts" setup>
import {h, reactive} from 'vue';
import {MailOutlined, AppstoreOutlined, SettingOutlined} from '@ant-design/icons-vue';
import {ItemType} from 'ant-design-vue';

const items: ItemType[] = reactive([
  {
    label: 'Navigation One',
    key: 'sub1',
    icon: () => h(MailOutlined),
    children: [
      {
        label: 'Option 1',
        key: '1',
      },
      {
        label: 'Option 2',
        key: '2',
      },
      {
        label: 'Option 3',
        key: '3',
      },
      {
        label: 'Option 4',
        key: '4',
      },
    ],
  },
  {
    label: 'Navigation Two',
    key: 'sub2',
    icon: () => h(AppstoreOutlined),
    children: [
      {
        label: 'Option 5',
        key: '5',
      },
      {
        label: 'Option 6',
        key: '6',
      },
      {
        label: 'Submenu',
        key: 'sub3',
        children: [
          {
            label: 'Option 7',
            key: '7',
          },
          {
            label: 'Option 8',
            key: '8',
          },
        ],
      },
    ],
  },
  {
    label: 'Navigation Three',
    key: 'sub4',
    icon: () => h(SettingOutlined),
    children: [
      {
        label: 'Option 9',
        key: '9',
      },
      {
        label: 'Option 10',
        key: '10',
      },
      {
        label: 'Option 11',
        key: '11',
      },
      {
        label: 'Option 12',
        key: '12',
      },
    ],
  },
]);

const state = reactive({
  rootSubmenuKeys: ['sub1', 'sub2', 'sub4'],
  openKeys: [] as any,
  selectedKeys: [] as any,
});
const onOpenChange = (openKeys: string[]) => {
  const latestOpenKey = openKeys.find((key) => state.openKeys.indexOf(key) === -1);

  if (state.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
    console.log('二次进入', openKeys);
    state.openKeys = openKeys;
  } else {
    console.log('首次进入', latestOpenKey);
    state.openKeys = latestOpenKey ? [latestOpenKey] : [];
  }
  console.log('openKeys', openKeys);
  console.log('latestOpenKey', latestOpenKey);
  console.log('state.openKeys', state.openKeys);
};
</script>
